<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div>
        <div class="form-group">
            <label for="username">用户名：</label>
            <input type="text" class="username" name="username" id="username" placeholder="请输入用户名">
            <span>*</span>

        </div>
    </div>

</body>
<script>
    //1.获得焦点事件
    let username = document.querySelector('.username')
    //addEventListener是一个侦听事件并处bai理du相应的函数
    username.addEventListener("focus", function (e) {
        //nextElementSibling属性只返回元素节点之后的兄弟元素节点（不包括文本节点、注释节点）
        let span = this.nextElementSibling
        span.innerHTML = 'input获得焦点了'

    })
    //2.输入事件
    username.addEventListener("input", function (e) {
        // let span = this.nextElementSibling
        //span.innerHTML = this.value
        validUsername()
    })

    //3.失去焦点
    username.addEventListener("blur", function (e) {
        let span = this.nextElementSibling
        span.innerHTML = 'input失去焦点了'
    })
    //4.键盘事件
    username.addEventListener("keydown", function (e) {
        let keyCode = e.keyCode
        if (keyCode === 13) {
            let span = this.nextElementSibling
            span.innerHTML = '回车'
        }
    })
    /**
     * 描述  验证输入用户名是否符合要求  首位是字母
     * @date 2020-09-29
     * @returns {any}
     */
    function validUsername() {
        let v = username.value
        let span = username.nextElementSibling
        span.innerHTML = ''
        span.style.color = 'red'
        //判断空
        if (v.trim() === '') {
            span.innerHTML = '用户名不能为空'
            return false
        }
        //判断首位字母
        let code = v[0]
        let str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
        if (str.indexOf(code) === -1) {
            span.innerHTML = '用户名首位必须是字母'
            return false
        }
        //判断长度
        if (v.length > 12 || v.length < 6) {
            span.innerHTML = '用户名长度6-12位'
            return false
        }
        span.innerHTML = '用户名正确'
        span.style.color = 'green'
        return true
    }
</script>

</html>